package com.zzz.springsecuritystudy.filter;

import com.zzz.springsecuritystudy.constant.SecurityConstants;
import com.zzz.springsecuritystudy.entity.CheckResult;
import com.zzz.springsecuritystudy.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhuzhizun
 * @date 2021/9/15
 */

@Slf4j
public class TokenFilter extends GenericFilterBean {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //获取请求头 Authentication
        String authHeader = request.getHeader(SecurityConstants.HEADER);
        //获取请求体 Bearer token
        if (authHeader != null && authHeader.startsWith(SecurityConstants.TOKEN_SPLIT)) {
            // 获取真正的token
            final String authToken = authHeader.substring(SecurityConstants.TOKEN_SPLIT.length());
            // 验证token
            CheckResult checkResult = JwtUtils.validateJWT(authToken);
            // 获取用户名
            String username = checkResult.getClaims().getSubject();

            UsernamePasswordAuthenticationToken authentication;
            // 从redis中获取token  判断token和当前的token是否相等    username ---------> token
            if (checkResult.isSuccess() && true) {



                // 从claim中 获取角色信息
                String role = (String) checkResult.getClaims().get(SecurityConstants.ROLE_CLAIMS);
                // 封装角色信息
                List<SimpleGrantedAuthority> authorities = Arrays.stream(role.split(","))
                        .map(SimpleGrantedAuthority::new)
                        .collect(Collectors.toList());

                // 封装UsernamePasswordAuthenticationToken
                authentication = new UsernamePasswordAuthenticationToken(username, authToken, authorities);
                // 加入上下文中
                SecurityContextHolder.getContext().setAuthentication(authentication);
                log.info("tokenFilter-------通过");
            }


        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
